package com.cnyz.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.cnyz.exception.BaseException;
import com.cnyz.utils.FileUtil;
import com.cnyz.utils.ObjectUtil;
import com.cnyz.utils.UUID;
import com.cnyz.vo.UploadVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileUploadServiceImp implements com.cnyz.service.FileUploadService {

    @Value("${spring.upload.path}")
    private String diskPath;//  /upload/

    @Value("${spring.upload.url}")
    private String uploadUrl; // http://localhost:8080/upload/static/

    @Override
    public UploadVo uploadFile(MultipartFile file) {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID()+suffix;//文件名更改
        String contentType = file.getContentType();//文件类型
        String typeDir = null;
        System.out.println("文件类型"+contentType);

        if(ObjectUtil.isEmpty(contentType)){
            throw new BaseException("文件不能为空");
        }

        if(contentType.startsWith("video")){
            typeDir ="/video";
        }//video/mp4
        else if(contentType.startsWith("image")){
            typeDir ="/image";
        }//image/png
        else if(contentType.startsWith("application/pdf")){
            typeDir="/pdf";
        }//application/pdf
        else{
            throw new BaseException("不支持的文件类型");
        }

        String Path = typeDir +"/"+fileName;//类型文件夹+文件名
        Path filePath = Paths.get(diskPath,typeDir, fileName); //使用Paths获取文件路径

        try{
            Files.createDirectories(filePath.getParent()); //创建目录
            file.transferTo(filePath.toFile()); //将文件写入到指定路径
        }
        catch(Exception e){
            throw new BaseException("文件上传失败");
        }


        UploadVo uploadVo = new UploadVo();
        uploadVo.setPath(uploadUrl+Path);//线上资源挂载路径
        uploadVo.setType(contentType);
        uploadVo.setFileSize(file.getSize()+"字节");

        if(StringUtils.equals(typeDir,"/pdf")){
            //pdf文件读取测试
            String text= FileUtil.extractTextFromPdf(filePath.toString());
            uploadVo.setText(text);
        }
        if(StringUtils.equals(typeDir,"/video")){
            System.out.println("视频转文本");
            uploadVo.setText("文件转录中，请稍后查看");
        }

        return uploadVo;

    }//上传文件



}
